# COUNTDOWN VIEW
# -----------------------------------------------------------------------------
# This is the countdown view.

class AboutView extends window.App.BaseView

    # Init the view.
    init: =>
        @setDom ["#cdTitle", "#cdTimer", "#cdMilliseconds"]
        @setEvents()

    # Bind events to DOM elements.
    setEvents: =>
        @dom.cdTimer.countdown()


    # CREATE COUNTDOWN
    # -------------------------------------------------------------------------

    # When user clicks the "Create" button, validate the [Countdown](countdown.html), save
    # to the server and redirect to the countdown page.
    createClick: (e) =>
        @validateForm()

    # Validate the form before sending to the server.
    validateForm: =>
        now = new Date()
        targetDate = @dom.txtCdDate.datetimepicker "getDate"

        # Title can't be empty.
        if @dom.txtCdTitle.val().length < 1
            @warnField @dom.txtCdTitle
            return

        # Date must be valid future date.
        if @dom.txtCdDate.val().length < 10 or targetDate < now
            @warnField @dom.txtCdDate
            return

        # All good? Then proceed with form submission.
        @submitForm()

    # Submit the form. This will create a [Countdown](countdown.html) model and call
    # its `save` method. If successful, redirect to the countdown page, otherwise
    # show the error message to the user.
    submitForm: =>
        targetDate = @dom.txtCdDate.datetimepicker "getDate"

        cd = new App.Countdown()
        cd.set "targetDate", targetDate
        cd.set "title", @dom.txtCdTitle

        cd.save {onSuccess: @saveOk, onError: @saveError}

        @dom.butCdSubmit.prop "disabled", true

    # Callback for successful save, redirect the user to the countdown page.
    saveOk: (cd, data) =>
        window.document.location.href = "/" + cd.friendlyUrl()

    # Callback for error when saving, show the error message to the user.
    saveError: (cd, error) =>
        alert error


# APPEND VIEW TO WINDOW
# -----------------------------------------------------------------------------
window.App.currentView = new AboutView()